package org.filehanding.util;

import org.apache.log4j.Logger;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by liguo on 2016/5/14.
 */
public class PassUtil {
    private static Logger log = Logger.getLogger(PassUtil.class);
    /**
     * 加密密码
     *
     * @param password
     * @return
     * @throws Exception
     */
    public static String getEncryptPassword(String password)  {
        String str = encodeByMD5(password, "utf-8");
        return encodeBySHA(str, "utf-8");
    }

    /**
     * 使用MD5算法加密
     *
     * @param str
     * @param charset
     * @return
     * @throws Exception
     */
    public static String encodeByMD5(String str, String charset)  {
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.reset();
            messageDigest.update(str.getBytes(charset));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            log.info("不能调用MD5加密算法。");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            log.info("字符串不支持" + charset + "的转换。");
        }
        return byteArrayToString(messageDigest.digest());
    }
    /**
     * 使用SHA算法加密
     *
     * @param str
     * @param charset
     * @return
     * @throws Exception
     */
    public static String encodeBySHA(String str, String charset) {
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance("SHA");
            messageDigest.reset();
            messageDigest.update(str.getBytes(charset));

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            log.info("不能调用MD5加密算法。");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            log.info("字符串不支持" + charset + "的转换。");
        }
        return byteArrayToString(messageDigest.digest());
    }
    /**
     * 将byte数组转化为16进制字符串
     *
     * @param byteArray
     * @return
     */
    private static String byteArrayToString(byte[] byteArray) {
        StringBuilder strBuilder = new StringBuilder();
        for (int i = 0; i < byteArray.length; i++) {
            if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
                strBuilder.append("0").append(
                        Integer.toHexString(0xFF & byteArray[i]));
            else
                strBuilder.append(Integer.toHexString(0xFF & byteArray[i]));
        }
        return strBuilder.toString();
    }
}
